const fs = require('fs-extra');
const path = require('path');
const ExcelJS = require('exceljs');
const testCaseResult = {
  succeed: '通过',
  nonStrictSucceed: '通过*',
  failed: '未通过',
  exception: '执行异常',
  codeDefect: '运行时错误',
  noResult: '无结果',
};
class ZhongHeExcel {
  constructor(username = 'rocket') {
    this.workbook = new ExcelJS.Workbook();
    this.workbook.creator = username;
    this.workbook.lastModifiedBy = username;
    this.workbook.created = new Date();
    this.workbook.modified = new Date();

    this.lastSheet = null;
  }

  /**
   * 添加工作表
   * @param {String} sheetName 工作表名
   * @return {Object}
   */
  addSheet(sheetName) {
    this.lastSheet = this.workbook.addWorksheet(sheetName);
    return this.lastSheet;
  }

  /**
   * 设置单元格
   * @param {String} position 位置
   * @param {String} value 值
   * @param {Object} font 字体
   * @param {Object} alignment 对齐方式
   * @param {Object} fill 样式
   * @param {Object} border 边框样式
   */
  setCell(
    position,
    {
      value = undefined,
      font = { name: '宋体' },
      alignment = { vertical: 'middle', horizontal: 'center' },
      fill = undefined,
      border = undefined,
      dataValidation = undefined,
    } = {},
  ) {
    const cell = this.lastSheet.getCell(position);
    if (value !== undefined && value !== null) {
      cell.value = value;
    }
    if (border) {
      cell.border = border;
    }
    if (font) {
      cell.font = font;
    }
    if (alignment) {
      cell.alignment = alignment;
    }
    if (fill) {
      cell.fill = fill;
    }
    if (dataValidation) {
      cell.dataValidation = dataValidation;
    }
  }

  /**
   * 添加图片到单元格
   * @param {object} sheet
   * @param {string} cellPosition 单元格位置
   * @param {buffer} imageBuffer 图片文件buffer
   * @param {string} extname 图片格式
   * @returns
   */
  addImageToCell(cellPosition, imageBuffer, extname) {
    const imageId = this.workbook.addImage({
      buffer: imageBuffer,
      extension: extname,
    });
    this.lastSheet.addImage(imageId, cellPosition);
    // return this.lastSheet.getCell(cellPosition);
  }

  /**
   * 合并单元格
   * @param {String} startPosition 起始点
   * @param {String} endPosition 终止点
   */
  mergeCells(startPosition, endPosition) {
    this.lastSheet.mergeCells(`${startPosition}:${endPosition}`);
  }

  /**
   * 写出excel表格文件
   * @param {String} outputPath 输出文件路径
   * @return {Promise}
   */
  writeFile(outputPath) {
    return this.workbook.xlsx.writeFile(outputPath);
  }

  /**
   * 添加修订记录sheet页
  */
  addRevisionRecordSheet() {
    const sheetName = '修订记录';
    this.addSheet(sheetName);
    // 设置行高
    this.lastSheet.getRow(2).height = 41;
    // 设置列宽
    this.lastSheet.getColumn(1).width = 7;
    this.lastSheet.getColumn(2).width = 15;
    this.lastSheet.getColumn(3).width = 11;
    this.lastSheet.getColumn(4).width = 28;
    this.lastSheet.getColumn(5).width = 10;
    [3, 4, 5, 6, 7, 8, 9].forEach((columnNumber) => {
      this.lastSheet.getColumn(columnNumber).height = 15;
    });

    const alignment = { vertical: 'middle', horizontal: 'center' };
    // 填充图片
    const logoImageBuffer = fs.readFileSync(path.join(__dirname, 'images/logo.jpg'));
    // this.addImageToCell('B2:B2', logoImageBuffer, 'jpg');
    this.addImageToCell({
      tl: { col: 0.5, row: 1 },
      ext: { width: 150, height: 50 },
    }, logoImageBuffer, 'jpg');
    // 设置标题
    const titleCell = this.lastSheet.getCell('D1');
    titleCell.font = {
      name: '宋体',
      size: 18,
      bold: true,
    };
    titleCell.value = '单元/软件集成测试用例';
    titleCell.alignment = { vertical: 'middle', horizontal: 'center' };

    // 填充特殊颜色
    const fillCellColor = {
      type: 'pattern',
      pattern: 'solid',
      fgColor: { argb: 'CCFFFF' },
    };
    // 单元格边框
    const cellBorderStyle = {
      top: { style: 'thin' },
      left: { style: 'thin' },
      bottom: { style: 'thin' },
      right: { style: 'thin' },
    };
    const borderBymedium = {
      top: { style: 'medium' },
      left: { style: 'medium' },
      bottom: { style: 'medium' },
      right: { style: 'medium' },
    };
    const mergeCellsArray = [
      'B5:B7', 'D3:F3', 'D4:F4', 'D5:F5', 'D6:F6', 'D7:F7',
      'A1:C2', 'D1:G2',
    ];
    // 填充内容
    for (let rowNumber = 3; rowNumber <= 24; rowNumber += 1) {
      const row = this.lastSheet.getRow(rowNumber);
      row.alignment = alignment;
      if (rowNumber === 3) {
        row.getCell(2).value = 'ZHKJ203710';
        row.getCell(2).border = cellBorderStyle;
        row.getCell(3).value = '项目名称';
        row.getCell(3).fill = fillCellColor;
        row.getCell(3).border = cellBorderStyle;
        row.getCell(4).value = '单元/软件集成测试用例';
        row.getCell(4).border = cellBorderStyle;
      }
      if (rowNumber === 4) {
        row.getCell(2).value = '文件状态';
        row.getCell(2).border = cellBorderStyle;
        row.getCell(3).value = '文件编号';
        row.getCell(3).fill = fillCellColor;
        row.getCell(3).border = cellBorderStyle;
        row.getCell(4).border = cellBorderStyle;
      }
      if (rowNumber === 5) {
        row.getCell(2).value = '已发布';
        row.getCell(2).dataValidation = {
          type: 'list',
          allowBlank: true,
          formulae: ['"草稿,修订中,已发布"'],
        };
        row.getCell(2).border = cellBorderStyle;
        row.getCell(3).fill = fillCellColor;
        row.getCell(3).value = '当前版本';

        row.getCell(3).border = cellBorderStyle;
        row.getCell(4).border = cellBorderStyle;
      }
      if (rowNumber === 6) {
        row.getCell(2).border = cellBorderStyle;
        row.getCell(3).value = '批    准';
        row.getCell(3).fill = fillCellColor;
        row.getCell(3).border = cellBorderStyle;
        row.getCell(4).border = cellBorderStyle;
      }
      if (rowNumber === 7) {
        row.getCell(2).border = cellBorderStyle;
        row.getCell(3).border = cellBorderStyle;
        row.getCell(3).value = '文档密级';
        row.getCell(3).fill = fillCellColor;
        row.getCell(4).value = '秘密';
        row.getCell(4).dataValidation = {
          type: 'list',
          allowBlank: true,
          formulae: ['"普通,秘密,机密,绝密"'],
        };
        row.getCell(4).border = cellBorderStyle;
      }
      if (rowNumber === 9) {
        row.font = {
          name: '宋体',
          size: 11,
          bold: true,
        };
        row.getCell(1).value = '版本号';
        row.getCell(2).value = '修订章节';
        row.getCell(3).value = '修订内容';
        row.getCell(5).value = '修订日期';
        row.getCell(6).value = '修订人';
        row.getCell(7).value = '审核人';
        row.getCell(1).fill = fillCellColor;
        row.getCell(2).fill = fillCellColor;
        row.getCell(3).fill = fillCellColor;
        row.getCell(4).fill = fillCellColor;
        row.getCell(5).fill = fillCellColor;
        row.getCell(6).fill = fillCellColor;
        row.getCell(7).fill = fillCellColor;
        const topAndBottom = {
          top: borderBymedium.top,
          bottom: borderBymedium.bottom,
        };
        row.getCell(1).border = topAndBottom;
        row.getCell(2).border = topAndBottom;
        row.getCell(3).border = topAndBottom;
        row.getCell(4).border = topAndBottom;
        row.getCell(5).border = topAndBottom;
        row.getCell(6).border = topAndBottom;
        row.getCell(7).border = {
          top: borderBymedium.top,
          bottom: borderBymedium.bottom,
          right: borderBymedium.right,
        };
      }
      if (rowNumber === 10) {
        row.getCell(1).value = 'V0.0.1';
        row.getCell(3).value = '初稿';
      }
      if (rowNumber === 11) {
        row.getCell(1).value = 'V1.0';
        row.getCell(3).value = '正式发布';
      }
      if (rowNumber >= 9) {
        mergeCellsArray.push(`C${rowNumber}:D${rowNumber}`);
      }
      if (rowNumber > 9 && rowNumber < 24) {
        row.getCell(7).border = {
          right: borderBymedium.right,
        };
      }
      if (rowNumber === 24) {
        const bottomStyle = {
          bottom: borderBymedium.bottom,
        };
        row.getCell(1).border = bottomStyle;
        row.getCell(2).border = bottomStyle;
        row.getCell(3).border = bottomStyle;
        row.getCell(4).border = bottomStyle;
        row.getCell(5).border = bottomStyle;
        row.getCell(6).border = bottomStyle;
        row.getCell(7).border = {
          right: borderBymedium.right,
          bottom: borderBymedium.bottom,
        };
      }
    }
    ['D3', 'D4', 'D5', 'D6', 'D7'].forEach((cellNumber) => {
      this.setCell(cellNumber, {
        font: {
          name: '宋体',
          size: 11,
          bold: false,
        },
      });
    });
    ['B3', 'B4', 'B5', 'B6', 'B7', 'C3', 'C4', 'C5', 'C6', 'C7'].forEach((cellNumber) => {
      this.setCell(cellNumber, {
        font: {
          name: '宋体',
          size: 11,
          bold: true,
        },
      });
    });
    mergeCellsArray.forEach((cell) => {
      this.lastSheet.mergeCells(cell);
    });
  }

  /**
   * 添加函数名和sheet名映射
   */
  addFunctionNameAndSheetNameMapping(funcAndsheetMapping) {
    const sheetName = '函数名映射';
    this.addSheet(sheetName);
    const titleFont = {
      name: 'Arial',
      size: 18,
      bold: true,
    };
    const contentFont = {
      name: 'Arial',
      size: 11,
    };
    const alignment = { vertical: 'middle', horizontal: 'center' };
    this.lastSheet.getRow(1).height = 20;
    this.lastSheet.getColumn(1).width = 16;
    this.lastSheet.getColumn(2).width = 40;
    this.setCell('A1', { value: 'sheet名称', titleFont });
    this.setCell('B1', { value: '函数名', titleFont });
    for (let i = 0; i < funcAndsheetMapping.length; i += 1) {
      const rowData = funcAndsheetMapping[i];
      const rowNumber = i + 2;
      const row = this.lastSheet.getRow(rowNumber);
      row.getCell(1).value = rowData.number;
      row.getCell(1).font = contentFont;
      row.getCell(1).alignment = alignment;

      row.getCell(2).value = rowData.functionName;
      row.getCell(2).font = contentFont;
      row.getCell(2).alignment = alignment;
    }
  }

  /**
   * 添加总览sheet页
   * @param {Array[Object]} moduleDatas 函数/模块统计数据
  */
  addSummarySheet(moduleDatas) {
    const sheetName = 'summarytable';
    this.addSheet(sheetName);
    // 设置行高
    this.lastSheet.getRow(1).height = 80;
    this.lastSheet.getRow(2).height = 27;
    this.lastSheet.getRow(3).height = 24;
    this.lastSheet.getRow(4).height = 33;
    // 设置列宽
    this.lastSheet.getColumn(1).width = 16;
    this.lastSheet.getColumn(2).width = 32;
    this.lastSheet.getColumn(3).width = 34;

    const fillColorBgByBlackishGreen = {
      type: 'pattern',
      pattern: 'solid',
      fgColor: { argb: '4BACC6' },
    };
    const borderBymedium = {
      top: { style: 'medium' },
      left: { style: 'medium' },
      bottom: { style: 'medium' },
      right: { style: 'medium' },
    };
    const borderBythin = {
      top: { style: 'thin' },
      left: { style: 'thin' },
      bottom: { style: 'thin' },
      right: { style: 'thin' },
    };
    const fillBgColorByGreen = {
      type: 'pattern',
      pattern: 'solid',
      fgColor: { argb: '92D050' },
    };
    const fillBgColorByRed = {
      type: 'pattern',
      pattern: 'solid',
      fgColor: { argb: 'C0504D' },
    };
    // 填充固定内容
    this.setCell('A1', {
      value: '填写说明：',
      fill: fillBgColorByGreen,
    });
    this.setCell('B1', {
      value: '1、该表填写单元测试所需的所有函数。一个函数对应一张sheet,一个Excel文件对应一个模块。\n2、该表填写软件集成测试所需测试的所有模块。一个模块对应一张sheet,一个Excel文件对应一个项目。',
      fill: fillBgColorByGreen,
      alignment: {
        vertical: 'top',
        horizontal: 'left',
        wrapText: true,
      },
    });
    this.setCell('A2', {
      value: '参考文档',
      font: {
        name: '宋体',
        size: 11,
        color: { argb: 'FFFFFF' },
      },
      border: borderBymedium,
      fill: fillBgColorByRed,
    });
    this.setCell('B2', {
      value: '请填写对应的详细（概要）设计规格书、测试规格书的名称及版本',
      border: borderBymedium,
      fill: fillColorBgByBlackishGreen,
    });
    this.setCell('A3', {
      value: '信息表',
      font: {
        name: '宋体',
        size: 18,
        bold: true,
      },
      border: borderBymedium,
      fill: {
        type: 'pattern',
        pattern: 'solid',
        fgColor: { argb: 'F1F5BD' },
      },
    });
    this.setCell('A4:A4', {
      value: '序号',
      font: {
        name: '宋体',
        size: 11,
        color: { argb: 'FFFFFF' },
      },
      border: borderBymedium,
      fill: fillBgColorByRed,
    });
    this.setCell('B4', {
      value: '函数或模块名称',
      font: {
        name: '宋体',
        size: 11,
        color: { argb: 'FFFFFF' },
      },
      border: borderBymedium,
      fill: fillBgColorByRed,
    });
    this.setCell('C4', {
      value: 'case数',
      font: {
        name: '宋体',
        size: 11,
        color: { argb: 'FFFFFF' },
      },
      border: borderBymedium,
      fill: fillBgColorByRed,
    });
    // 合并单元格
    this.lastSheet.mergeCells('B1', 'C1');
    this.lastSheet.mergeCells('B2', 'C2');
    this.lastSheet.mergeCells('A3', 'C3');
    const startRowNumber = 5;
    for (let rowNumber = 0; rowNumber < moduleDatas.length; rowNumber += 1) {
      const rowData = moduleDatas[rowNumber];
      const row = this.lastSheet.getRow(startRowNumber + rowNumber);
      // 填充序号
      row.getCell(1).value = rowNumber + 1;
      row.getCell(1).border = borderBythin;
      row.getCell(1).fill = fillColorBgByBlackishGreen;
      row.getCell(1).font = {
        name: '宋体',
        size: 11,
        color: { argb: 'FFFFFF' },
      };
      row.getCell(1).alignment = { vertical: 'middle', horizontal: 'center' };
      // 填充模块/函数
      row.getCell(2).value = rowData.moduleName;
      row.getCell(2).border = borderBythin;
      row.getCell(2).fill = fillColorBgByBlackishGreen;
      row.getCell(2).font = {
        name: '宋体',
        size: 11,
        color: { argb: 'FFFFFF' },
      };
      row.getCell(2).alignment = { vertical: 'middle', horizontal: 'center' };
      // 用例个数
      row.getCell(3).value = rowData.testCaseCount;
      row.getCell(3).border = borderBythin;
      row.getCell(3).fill = fillColorBgByBlackishGreen;
      row.getCell(3).font = {
        name: '宋体',
        size: 11,
        color: { argb: 'FFFFFF' },
      };
      row.getCell(3).alignment = { vertical: 'middle', horizontal: 'center' };
    }
  }

  /**
   *函数sheet页基础数据
   */
  funcTestCaseSheetBase(functionName) {
    this.lastSheet.getRow(1).height = 120;
    this.lastSheet.getRow(2).height = 24;
    this.lastSheet.getColumn('A').width = 40;
    this.lastSheet.getColumn('D').width = 38;
    ['B', 'C', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N'].forEach((colName) => {
      this.lastSheet.getColumn(colName).width = 18;
    });
    const fillBgByLightGreen = {
      type: 'pattern',
      pattern: 'solid',
      fgColor: { argb: 'C6EFCE' },
    };
    const fillBgByDarkGreen = {
      type: 'pattern',
      pattern: 'solid',
      fgColor: { argb: '339966' },
    };
    const fillBgByYellow = {
      type: 'pattern',
      pattern: 'solid',
      fgColor: { argb: 'FFFF99' },
    };
    const borderBythin = {
      top: { style: 'thin' },
      left: { style: 'thin' },
      bottom: { style: 'thin' },
      right: { style: 'thin' },
    };
    const title2Style = {
      font: {
        name: '宋体',
        size: 12,
        bold: true,
      },
      border: borderBythin,
      fill: fillBgByYellow,
    };
    const title3Font = {
      name: '宋体',
      size: 11,
      bold: true,
    };
    this.setCell('A1', {
      value: '填写说明：',
      fill: fillBgByLightGreen,
    });
    this.setCell('B1', {
      value: '1、用例ID:根据REQTIFY工具文档编号标识规则编写\n'
           + '2、用例追溯信息：填写追溯源头对应编号\n'
           + '3、用例名：若单元测试则填写函数名，若软件集成测试则填写模块名\n'
           + '4、前置条件：对“操作”的描述可以写在预置条件中\n'
           + '5、测试结果：测试时填写，也可体现在测试报告中\n'
           + '6、“条件恢复”列仅用于软件集成测试；',
      fill: fillBgByLightGreen,
      alignment: {
        vertical: 'top',
        horizontal: 'left',
        wrapText: true,
      },
    });
    this.setCell('A2', {
      value: functionName,
      fill: fillBgByDarkGreen,
      font: {
        name: '宋体',
        size: 18,
        bold: true,
      },
    });
    [
      'A3:用例ID', 'B3:用例追溯信息', 'C3:用例名', 'D3:前置条件',
      'E3:输入', 'G3:预期输出', 'J3:测试结果', 'K3:条件恢复', 'L3:测试者',
      'M3:测试时间', 'N3:备注', 'E4:输入名', 'F4:值', 'G4:输出名',
      'H4:预期值', 'I4:实际值'].forEach((item) => {
      const [index, value] = item.split(':');

      if (['E3', 'G3'].includes(index)) {
        const newStyle = {
          font: title2Style.font,
          border: title2Style.border,
          fill: fillBgByDarkGreen,
        };
        this.setCell(index, {
          value,
          ...newStyle,
        });
      } else if (['E4', 'F4', 'G4', 'H4', 'I4'].includes(index)) {
        const newStyle = {
          font: title3Font,
          border: title2Style.border,
          fill: fillBgByYellow,
        };
        this.setCell(index, {
          value,
          ...newStyle,
        });
      } else {
        this.setCell(index, {
          value,
          ...title2Style,
        });
      }
    });
    // 合并单元格
    [
      'B1:N1', 'A2:N2', 'A3:A4',
      'B3:B4', 'C3:C4', 'D3:D4',
      'E3:F3', 'G3:I3', 'J3:J4',
      'K3:K4', 'L3:L4', 'M3:M4',
      'N3:N4'].forEach((item) => {
      const [start, end] = item.split(':');
      this.mergeCells(start, end);
    });
  }

  /**
   * 添加函数测试用例sheet页
   * @param {Object} funcTestCase 函数测试用例
  */
  addFuncTestCaseSheet(funcTestCase) {
    const { functionName, testCases, number } = funcTestCase;
    const splitStr = Date.now();
    this.addSheet(`${number}`);
    this.funcTestCaseSheetBase(functionName);
    const testCaseResults = ['"通过,通过*,不通过,执行异常,运行时错误,无结果"'];
    // 填充测试用例数据
    const testCaseCellStyle = {
      font: {
        name: '宋体',
        size: 11,
      },
      border: {
        top: { style: 'thin' },
        left: { style: 'thin' },
        bottom: { style: 'thin' },
        right: { style: 'thin' },
      },
      fill: {
        type: 'pattern',
        pattern: 'solid',
        fgColor: { argb: 'F2DCDB' },
      },
    };
    // 测试用例开始填充的行
    let rowNumber = 5;
    testCases.forEach((testCase) => {
      // 填充基础数据列
      [
        `A${rowNumber}${splitStr}${testCase.Id}`,
        `B${rowNumber}${splitStr}${testCase.traceAbilityInfo}`,
        `C${rowNumber}${splitStr}${testCase.name}`,
        `D${rowNumber}${splitStr}${testCase.preConditions}`,
        `J${rowNumber}${splitStr}${testCase.result}`,
        `K${rowNumber}${splitStr}${testCase.conditionalRecovery}`,
        `L${rowNumber}${splitStr}${testCase.tester}`,
        `M${rowNumber}${splitStr}${testCase.testTime}`,
        `N${rowNumber}${splitStr}${testCase.remarks}`,
      ].forEach((cell) => {
        const [position, value] = cell.split(splitStr);
        if (position === `J${rowNumber}`) {
          this.setCell(position, {
            value,
            ...testCaseCellStyle,
            dataValidation: {
              type: 'list',
              allowBlank: true,
              formulae: testCaseResults,
            },
          });
        } else if (position === `D${rowNumber}`) {
          this.setCell(position, {
            value,
            ...testCaseCellStyle,
            alignment: {
              vertical: 'top',
              horizontal: 'left',
              wrapText: true,
            },
          });
        } else {
          this.setCell(position, {
            value,
            ...testCaseCellStyle,
          });
        }
      });
      // 填充输入输出值列
      const { input, output } = testCase;
      if (input.length === 0) {
        input.push({
          name: '',
          value: '',
        });
      }
      for (let i = 0; i < input.length; i += 1) {
        const inputDataOfCell = input[i];
        const outputDataOfCell = output[i];
        [
          `E${rowNumber}${splitStr}${inputDataOfCell.name}`,
          `F${rowNumber}${splitStr}${inputDataOfCell.value}`,
          `G${rowNumber}${splitStr}${outputDataOfCell ? outputDataOfCell.name : ''}`,
          `H${rowNumber}${splitStr}${outputDataOfCell ? outputDataOfCell.expectedValue : ''}`,
          `I${rowNumber}${splitStr}${outputDataOfCell ? outputDataOfCell.actualValue : ''}`,
        ].forEach((item) => {
          const [position, value] = item.split(splitStr);
          this.setCell(position, {
            value,
            ...testCaseCellStyle,
          });
        });
        rowNumber += 1;
      }
      // 合并单元格
      const startRowNumber = rowNumber - input.length;
      const endRowNumber = rowNumber - 1;
      if (startRowNumber === endRowNumber) {
        return;
      }
      const testCaseMergeCells = [
        `A${startRowNumber}:A${endRowNumber}`,
        `B${startRowNumber}:B${endRowNumber}`,
        `C${startRowNumber}:C${endRowNumber}`,
        `D${startRowNumber}:D${endRowNumber}`,
        `J${startRowNumber}:J${endRowNumber}`,
        `K${startRowNumber}:K${endRowNumber}`,
        `L${startRowNumber}:L${endRowNumber}`,
        `M${startRowNumber}:M${endRowNumber}`,
        `N${startRowNumber}:N${endRowNumber}`,
      ];
      if (output.length <= 1) {
        testCaseMergeCells.push(...[
          `G${startRowNumber}:G${endRowNumber}`,
          `H${startRowNumber}:H${endRowNumber}`,
          `I${startRowNumber}:I${endRowNumber}`,
        ]);
      }
      testCaseMergeCells.forEach((item) => {
        const [start, end] = item.split(':');
        this.mergeCells(start, end);
      });
    });
  }

  /**
 * 格式化测试用例前置条件数据
 */
  static getPreConditionsData(inputData) {
    let inputStr = '';
    let categoryState = false;
    inputData.forEach((item) => {
      if (item.category && item.category !== '' && item.category !== '形参') {
        let enter = '\n';
        if (categoryState) {
          enter = '\n\n';
        }
        inputStr = inputStr === '' ? item.category : `${inputStr}${enter + item.category}`;
        categoryState = false;
      }
      if (item.variable && item.variable !== '') {
        inputStr += `\n  ${item.variable}`;
        categoryState = true;
      }
      if (item.variable && item.value === '') {
        inputStr += ';';
      }
      if (item.value && item.value !== '') {
        inputStr += `=${item.value};`;
        categoryState = true;
      }
      if (item.result && item.result !== '') {
        categoryState = true;
      }

      if (item.location) {
        const begin = `起始(${item.location.begin.line},${item.location.begin.column});`;
        const end = `结束(${item.location.end.line},${item.location.end.column})`;
        inputStr += `\n  ${begin + end}`;
        categoryState = true;
      }
    });

    return inputStr;
  }

  /**
   *
   *导出单文件表格
   * @param {*} reportPath
   * @param {*} data
 */
  generateFileReport(reportPath, data) {
    const fileSummary = [];
    const funcsData = [];
    let number = 0;
    const funcAndsheetMapping = [];
    data.forEach((funcdata) => {
      const { functionName, tests: testCases } = funcdata;
      number += 1;
      fileSummary.push({
        moduleName: functionName,
        testCaseCount: testCases.length,
      });
      const func = {
        functionName,
        number,
        testCases: [],
      };
      testCases.forEach((testCase) => {
        const index = testCase.index < 10 ? `0${testCase.index}` : testCase.index;
        const input = [];
        const output = [];
        let traceAbilityInfo;
        if (testCase.udfs) {
          testCase.udfs.forEach((udf) => {
            if (udf.name === '用例追溯信息') {
              traceAbilityInfo = udf.value;
            }
          });
        }
        let inputCategory;
        const preConditions = [];
        if (testCase.detail.input) {
          testCase.detail.input.forEach((item) => {
            inputCategory = item.category ? item.category : inputCategory;
            if (inputCategory === '形参') {
              input.push({
                name: item.variable,
                value: item.value,
              });
            } else {
              preConditions.push(item);
            }
          });
        }
        let outputCategory;
        if (testCase.detail.output) {
          testCase.detail.output.forEach((item) => {
            outputCategory = item.category ? item.category : outputCategory;
            if (outputCategory === '返回值') {
              output.push({
                name: item.variable,
                actualValue: item.result,
                expectedValue: item.value,
              });
            }
          });
        }
        func.testCases.push({
          Id: `[TestSuite_MON_${functionName}_${index}]`,
          name: functionName,
          traceAbilityInfo: traceAbilityInfo || '',
          preConditions: ZhongHeExcel.getPreConditionsData(preConditions),
          result: testCaseResult[testCase.resultKind],
          conditionalRecovery: '',
          tester: '',
          testTime: '',
          remarks: '',
          input,
          output,
        });
      });
      funcAndsheetMapping.push({
        functionName,
        number,
      });
      funcsData.push(func);
    });
    this.addRevisionRecordSheet();
    this.addFunctionNameAndSheetNameMapping(funcAndsheetMapping);
    this.addSummarySheet(fileSummary);
    funcsData.forEach((func) => {
      this.addFuncTestCaseSheet(func);
    });
    this.writeFile(reportPath);
  }
}

module.exports = ZhongHeExcel;
